<?php
require_once ($_SERVER["DOCUMENT_ROOT"] ."/include/config.php");

if (isset($_POST["op"])) {
	$controller = new DictionaryController($config);
	$controller -> ProcessRequest();
}

class DictionaryController {
	private $link;

	public function __construct($config) {

		if (!$this -> link = mysql_connect($config -> db_host, $config -> db_user, $config -> db_pass)) {
			echo "Не могу соединиться с сервером базы данных</p>";
			exit();
		}
		mysql_query("SET NAMES utf8;", $this->link);
		if (!mysql_select_db($config -> db_name, $this -> link)) {
			echo "Не могу соединиться с сервером базы данных</p>";
			exit();
		}
	}

	public function ProcessRequest() {
		if (isset($_POST["dict"])) {
			$dictName = $_POST["dict"];
			if ($_POST["op"] == "get")
				$this -> GetDictionary($_POST["dict"]);
			else if ($_POST["op"] == "del") {
				if (isset($_POST["id"]))
					$this -> DeleteEntry($_POST["dict"], $_POST["id"]);
			} else if ($_POST["op"] == "set") {
				if (isset($_POST["id"]) && isset($_POST["title"]))
					$this -> UpdateEntry($_POST["dict"], $_POST["id"], $_POST["title"]);
			}
			else if ($_POST["op"] == "add_color") {
				$this->AddColor($_POST["color"], $_POST["ring"]);
			}
		}
	}
	
	private function AddColor($color, $ring) {
		$query = "INSERT INTO colors (color) VALUES ('$ring$color');";
		mysql_query($query, $this -> link) or die(mysql_error());
	}

	private function GetTableName($dictName) {
		if ($dictName == "support_type")
			return "support_points_type";
		if ($dictName == "cable_params")
			return "cables_param_type";
		else return $dictName;
	}

	public function GetDictionary($dictName, $echo = true) {
		$table = $this -> GetTableName($dictName);
		$data = array();
		$query = "SELECT * FROM $table";
		$result = mysql_query($query, $this -> link);
		while ($row = mysql_fetch_object($result)) {
			if ($table == "colors")	$data[] = $row->color;
			else $data[$row->id] = $row->title;
		}
		if ($echo) 
			echo json_encode($data);
		return $data;
	}

	private function DeleteEntry($dictName, $id) {
		$table = $this -> GetTableName($dictName);
		if ($dictName != 'colors')
		$query = "DELETE FROM $table WHERE id = '$id'";
		else 
			$query = "DELETE FROM $table WHERE color = '$id'";
		mysql_query($query, $this -> link) or die(mysql_error());
		echo "Запись удалена";
	}

	private function UpdateEntry($dictName, $id, $title) {

		$table = $this -> GetTableName($dictName);
		$query = "INSERT INTO $table (id, title) VALUES ('$id', '$title')
	  	ON DUPLICATE KEY UPDATE title = '$title'";
		mysql_query($query, $this -> link) or die(mysql_error());
		echo "Success!";
	}

}
?>
